package handlers

import (
	"net/http"
	"product-management-system/config"
	"product-management-system/models"

	"github.com/gin-gonic/gin"
)

// CreateProduct 创建产品
func CreateProduct(c *gin.Context) {
	var product models.Product
	if err := c.ShouldBindJSON(&product); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的请求参数"})
		return
	}

	if result := config.DB.Create(&product); result.Error != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "产品创建失败"})
		return
	}

	c.JSON(http.StatusCreated, product)
}

// GetProduct 获取单个产品
func GetProduct(c *gin.Context) {
	id := c.Param("id")

	var product models.Product
	if result := config.DB.First(&product, id); result.Error != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "产品不存在"})
		return
	}

	c.JSON(http.StatusOK, product)
}

// ListProducts 获取产品列表
func ListProducts(c *gin.Context) {
	var products []models.Product
	if result := config.DB.Find(&products); result.Error != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "获取产品列表失败"})
		return
	}

	c.JSON(http.StatusOK, products)
}

// UpdateProduct 更新产品
func UpdateProduct(c *gin.Context) {
	id := c.Param("id")

	var product models.Product
	if result := config.DB.First(&product, id); result.Error != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "产品不存在"})
		return
	}

	if err := c.ShouldBindJSON(&product); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的请求参数"})
		return
	}

	if result := config.DB.Save(&product); result.Error != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "产品更新失败"})
		return
	}

	c.JSON(http.StatusOK, product)
}

// DeleteProduct 删除产品
func DeleteProduct(c *gin.Context) {
	id := c.Param("id")

	result := config.DB.Delete(&models.Product{}, id)
	if result.Error != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "产品删除失败"})
		return
	}

	if result.RowsAffected == 0 {
		c.JSON(http.StatusNotFound, gin.H{"error": "产品不存在"})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "产品已删除"})
}